package com.sg.common.empty.core;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.sg.common.empty.entity.PerfProperty;
import com.sg.common.empty.entity.Property;
import com.sg.common.empty.json.Permission;
import com.sg.common.empty.json.TableList;
import com.sg.common.empty.json.TreeList;
import com.sg.common.empty.service.CfgService;
import com.sg.common.login.service.OrgMemberService;
import com.sg.common.utils.Constant;
import com.sg.common.utils.Generate;
import com.sg.common.utils.JsUtil;
import com.sg.common.utils.StrUtil;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigList;
import com.typesafe.config.ConfigValue;

public class ListPageBuilder {
	String linkButton = JspUtil3.linkButton;
	String ROWNOTSELECTED_TRIP = JspUtil3.ROWNOTSELECTED_TRIP;
	String ADD_EDIT_TABLE = JspUtil3.ADD_EDIT_TABLE;
	String SCRIPT_START = "<script>";
	String SCRIPT_END = "</script>";
	String url;
	String pre;
	String from;
	CfgService service;
	OrgMemberService omService;
	// private Perf perf;
	Object bean;
	HttpServletRequest request;
	private String tableName;
	List<Permission> buttonPermission;
	List<Permission> specialPermission;
	List<Permission> perfPermission;
	TableList tl = null;
	List<PerfProperty> listPl;
	List<PerfProperty> searchPl;
	String route;
	String header;

	@SuppressWarnings("unchecked")
	// public static ListPageBuilder init(HttpServletRequest request,
	// CfgService service) throws IllegalAccessException,
	// InvocationTargetException, NoSuchMethodException,
	// InstantiationException, ClassNotFoundException {
	// ListPageBuilder one = new ListPageBuilder();
	// one.setTableName(Generate.generateWord(3));
	// one.url = request.getRequestURI();
	// one.buttonPermission = (List<Permission>) request
	// .getAttribute("buttonPermission");
	// one.specialPermission = (List<Permission>) request
	// .getAttribute("specialPermission");
	// one.perfPermission = (List<Permission>) request
	// .getAttribute("perfPermission");
	// one.setPerf((Perf) request.getAttribute("perf"));
	// one.bean = request.getAttribute("bean");
	// // 确定是否为弹出页面
	// one.from = request.getParameter("_from");
	//
	// // 配置文件路径
	// one.route = (String) request.getAttribute("conf.route");
	// one.header = (String) request.getAttribute("conf.header");
	//
	// one.pre = request.getParameter("p_re");
	// one.request = request;
	// String layout = one.getPerf().getLayout();
	// if (StringUtils.equals("treeList", one.getPerf().getKind())) {
	// TreeList tree = JSONObject.parseObject(layout, TreeList.class);
	// one.tl = tree.getTl();
	// } else if (StringUtils.equals("list", one.getPerf().getKind())) {
	// one.tl = JSONObject.parseObject(layout, TableList.class);
	// }
	// one.listPl = service.searches(one.bean, one.tl.getList());
	// one.searchPl = service.searches(one.bean, one.tl.getSearch());
	//
	// return one;
	//
	// }
	public static ListPageBuilder init(HttpServletRequest request,
			CfgService service, OrgMemberService omService)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, InstantiationException,
			ClassNotFoundException, ServletException, IOException {
		ListPageBuilder one = new ListPageBuilder();
		one.setTableName(Generate.generateWord(3));
		one.url = request.getRequestURI();
		one.request = request;
		// 配置文件路径
		one.route = (String) request.getAttribute("conf.route");
		one.header = (String) request.getAttribute("conf.header");

		String tableName = Constant.get(StrUtil.dot(one.header, "tn"));

		ConfigList dataList = Constant.getList(StrUtil.dot(one.route, "perf.data"));
		if (dataList != null) {
			for (int i = 0; i < dataList.size(); i++) {
				Config data = dataList.get(i).atKey("data");

				boolean isICanSee = DealPermission.init(request, service,
						omService,data,"data").getCanIn();
				if (isICanSee) {
					ConfigList listPn = Constant.getList(data, "data.listPn");
					one.listPl = service.emptySearches(request, tableName,
							listPn);

					ConfigList searchPn = Constant.getList(data,
							"data.searchPn");
					one.searchPl = service.emptySearches(request, tableName,
							searchPn);
					break;
				}
			}
		}

		return one;

	}

	public StringBuilder listJs() throws SecurityException,
			IllegalArgumentException, ClassNotFoundException,
			IllegalAccessException, InstantiationException,
			NoSuchFieldException, InvocationTargetException,
			NoSuchMethodException {
		StringBuilder js = new StringBuilder();
		js.append(searJs());
		String autoSear = "1";
		if (StringUtils.equals(autoSear, "1")) {
			js.append(searInitJs());
		}
		return js;
	}

	/**
	 * 导出js 因为需要后台进行参数拼接，所以必须使用后台生成
	 * 
	 * @param tableName
	 * @param url
	 * @param searchPl
	 * @param pre
	 * @return
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws ClassNotFoundException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public StringBuilder exportXlsJs() throws SecurityException,
			NoSuchFieldException, ClassNotFoundException,
			IllegalArgumentException, IllegalAccessException {
		StringBuilder res = new StringBuilder();
		StringBuilder params = new StringBuilder();
		String expUrl = url.replace("find", "exp");
		for (PerfProperty pp : searchPl) {
			Property property = pp.getProperty();
			String field = property.getProperty();
			if (StringUtils.isNotEmpty(property.getVotype())) {// 对于类搜索，类的id作为搜索条件
				field += ".id";
			}
			params.append("'").append(field).append("':").append("$('#")
					.append(getTableName()).append("_tb input[name=\"")
					.append(field).append("\"]').val(),");
		}

		params.append("'_sql':$('#sql').val(),");
		if (StrUtil.requestParamsNotEmpty(pre)) {
			// String[] rs = StringUtils.split(pre, "$");
			// params.append("'").append(rs[0]).append("':").append(rs[1]).append(",");
			params.append("'p_re':'").append(pre).append("',");
		}
		if (StringUtils.isNotEmpty(params.toString())) {
			params.deleteCharAt(params.length() - 1);
		}
		res.append("function ")
				.append(getTableName())
				.append("_exp(){var rows = $('#")
				.append(getTableName())
				.append("').datagrid('getSelections');  if(rows.length>0){var ids=''; for(var i=0; i<rows.length; i++){ if(ids=='') ids=rows[i].id;else ids = ids+','+rows[i].id;}$.post('")
				.append(expUrl)
				.append("',{'_ids':ids},function(json){if(json=='false') alert('不能勾选导出，请直接导出！'); else window.open('"
						+ Constant.get("URL")
						+ "download?_exportUrl='+json);});")
				.append("}else{$.post('")
				.append(expUrl)
				.append("',{")
				.append(params)
				.append("},function(json){window.open('" + Constant.get("URL")
						+ "download?_exportUrl='+json);});}}");
		return res;
	}

	private Object searInitJs() {
		StringBuilder res = new StringBuilder();
		res.append("$(function(){setTimeout(\"")
				.append(JspUtil3.tableListJsMethod(getTableName()))
				.append(";\",500);});");
		return res;
	}

	// public StringBuilder listBody() throws IllegalAccessException,
	// InvocationTargetException, NoSuchMethodException,
	// NoSuchFieldException, SecurityException, IllegalArgumentException,
	// ClassNotFoundException {
	// StringBuilder res = new StringBuilder();
	// res.append(tableHtml());
	// res.append("<div id='")
	// .append(JspUtil3.listTableToolBarName(getTableName()))
	// .append("'>");
	// res.append(toolBarButton()).append(toolBarSearch()).append("</div>");
	// return res;
	// }

	public StringBuilder emptyListBody() throws IllegalAccessException,
			InvocationTargetException, NoSuchMethodException,
			NoSuchFieldException, SecurityException, IllegalArgumentException,
			ClassNotFoundException, ServletException, IOException,
			InstantiationException {
		StringBuilder res = new StringBuilder();
		res.append(tableHtml());
		res.append("<div id='")
				.append(JspUtil3.listTableToolBarName(getTableName()))
				.append("'>");
		res.append(emptyToolBarButton()).append(toolBarSearch())
				.append("</div>");
		return res;
	}

	public StringBuilder tableHtml() {
		StringBuilder table = new StringBuilder();
		table.append("<table id='").append(getTableName())
				.append("'></table><input type=\"hidden\" id=\"ids\">");
		StringBuilder res = new StringBuilder();
		if (StrUtil.requestParamsNotEmpty(from)) {
			res.append("<div style=\"height: 600px;\">")
					.append(table)
					.append("</div>")
					.append("<div id='bt' style=\"height: 50px; width :1000px\"></div>");
		} else {
			res.append(table);
		}
		return res;
	}

	/**
	 * 列表页面 搜索框
	 * 
	 * @param ppl
	 * @param bean
	 * @param quotePropertyId
	 * @return
	 * @throws ClassNotFoundException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public StringBuilder toolBarSearch() throws IllegalAccessException,
			InvocationTargetException, NoSuchMethodException,
			NoSuchFieldException {
		StringBuilder orgfilter = new StringBuilder();
		for (PerfProperty pp : searchPl) {
			// final Property property = pp.getProperty();
			// String[] beanValue = JspUtil3.filedVal(bean, pp);
			String dftValue = pp.getDftvalue();
			// TODO 查找
			String[] beanValue = { dftValue, "" };
			// if (property.getId().equals(quotePropertyId)) {
			// 如果这个属性就是引用页面的关联属性，则在搜索栏加入其hiddenValue
			// pp.setEsh("0");
			// 找到关联属性的值
			// }
			// findInput(pp, beanValue, "toolbar", false)
			orgfilter.append(
					new MyinputBuilder(pp, beanValue, "toolbar", false, "")
							.findInput()).append("&nbsp;");
		}
		StringBuilder res = new StringBuilder("<div style='margin-bottom:5px'>");

		res.append(orgfilter);

		res.append("</div>");
		return res;
	}

	/**
	 * 列表页面 搜索框
	 * 
	 * @param ppl
	 * @param bean
	 * @param quotePropertyId
	 * @return
	 * @throws ClassNotFoundException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public StringBuilder emptyToolBarSearch() throws IllegalAccessException,
			InvocationTargetException, NoSuchMethodException,
			NoSuchFieldException {
		StringBuilder orgfilter = new StringBuilder();
		for (PerfProperty pp : searchPl) {
			// final Property property = pp.getProperty();
			String[] beanValue = JspUtil3.filedVal(bean, pp);
			// if (property.getId().equals(quotePropertyId)) {
			// 如果这个属性就是引用页面的关联属性，则在搜索栏加入其hiddenValue
			// pp.setEsh("0");
			// 找到关联属性的值
			// }
			// findInput(pp, beanValue, "toolbar", false)
			orgfilter.append(
					new MyinputBuilder(pp, beanValue, "toolbar", false, "")
							.findInput()).append("&nbsp;");
		}
		StringBuilder res = new StringBuilder("<div style='margin-bottom:5px'>");

		res.append(orgfilter);

		res.append("</div>");
		return res;
	}

	/**
	 * 列表页面 按钮：1、常规按钮 2、特殊按钮 3、打印、搜索、刷新
	 * 
	 * @param tableName
	 * @param bean
	 * @param pid
	 * @param buttonPermission
	 * @param specialPermission
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws NoSuchFieldException
	 * @throws IllegalAccessException
	 */
	// public StringBuilder toolBarButton() throws SecurityException,
	// IllegalArgumentException, NoSuchFieldException,
	// ClassNotFoundException, IllegalAccessException {
	// StringBuilder plain = new StringBuilder(
	// "<div style='margin-bottom:5px'>");
	// String toolBar = request.getParameter("toolBar");
	// if (StringUtils.isEmpty(toolBar)
	// || StringUtils.equalsIgnoreCase(toolBar, "1")) {
	// for (Permission p : buttonPermission) {
	// // String actionName = p.getActionname();
	// String uri2 = p.getUri2();
	// String jsName = getTableName() + "_" + uri2 + "()";
	// if (uri2.equals("detail")) {
	// plain.append(linkButton).append(jsName).append("'>")
	// .append(Constant.get("JSP_DETAIL")).append("</a>");
	// plain.append(JsUtil.addScript(openUrlByOneRowJs(
	// getTableName(), jsName, JspUtil3.permissionUrl(p))));
	// } else if (uri2.equals("del")) {
	// plain.append(linkButton).append(jsName).append("'>")
	// .append(Constant.get("JSP_DEL")).append("</a>");
	// plain.append(JsUtil.addScript(findDelJs(getTableName(),
	// jsName, JspUtil3.permissionUrl(p))));
	// } else if (uri2.equals("add")) {
	// plain.append(linkButton).append(jsName).append("'>")
	// .append(Constant.get("JSP_ADD")).append("</a>");
	// plain.append(JsUtil.addScript(findAddJs(jsName,
	// JspUtil3.permissionUrl(p), bean, request)));
	// String cpjsName = getTableName() + "_cp_" + uri2 + "()";
	// plain.append(linkButton).append(cpjsName).append("'>")
	// .append(Constant.get("JSP_COPY")).append("</a>");
	// plain.append(JsUtil.addScript(openUrlByOneRowJs(
	// getTableName(), cpjsName, JspUtil3.permissionUrl(p))));
	// } else if (uri2.equals("edit")) {
	// plain.append(linkButton).append(jsName).append("'>")
	// .append(Constant.get("JSP_EDIT")).append("</a>");
	// plain.append(JsUtil.addScript(openUrlByOneRowJs(
	// getTableName(), jsName, JspUtil3.permissionUrl(p))));
	// } else if (uri2.equals("batch")) {
	// plain.append(linkButton).append(jsName).append("'>")
	// .append(Constant.get("JSP_BATCHEDIT"))
	// .append("</a>");
	// plain.append(JsUtil.addScript(openUrlByOneRowJs(
	// getTableName(), jsName, JspUtil3.permissionUrl(p))));
	// } else if (uri2.equals("exp")) {
	// plain.append(linkButton).append(jsName).append("'>")
	// .append("导出").append("</a>");
	// plain.append(JsUtil.addScript(exportXlsJs()));
	// } else {
	// plain.append(linkButton).append(jsName).append("'>")
	// .append(p.getDescr()).append("</a>");
	// plain.append(JsUtil.addScript(openUrlByOneRowJs(
	// getTableName(), jsName, JspUtil3.permissionUrl(p))));// TODO
	// // 设定button的访问后台方式--visitType---设定在对应的PERF显示方式中？
	// }
	// }
	// plain.append(JspUtil3.showSpecial(getPerf().getId(),
	// specialPermission));
	// plain.append(JspUtil3.buildPerfpermission(getPerf().getId(),
	// perfPermission, getTableName(), ""));
	// }/*
	// * else{
	// * //用于详细页面，关联字表的list页面，关闭子表的增加/修改权限：toolBar属性为0时，不显示增加，修改，删除，批量增加等按钮 }
	// */
	//
	// plain.append(linkButton).append("window.print();'>打印</a>");
	// plain.append(linkButton)
	// .append(JspUtil3.tableListJsMethod(getTableName()))
	// .append("' ><i class=\"icon-search\"></i>搜索</a>");
	//
	// plain.append(linkButton)
	// .append("javascript:window.document.location.reload()'><i class=\"icon-repeat\"></i>刷新</a>");
	// plain.append("</div>");
	// if (StrUtil.requestParamsNotEmpty(from)) {
	// plain.append(linkButton).append("df_cls()'>带值返回</a>");
	// plain.append(JsUtil.addScript(clsJs()));
	// }
	// return plain;
	// }

	/**
	 * 列表页面 按钮：1、常规按钮 2、特殊按钮 3、打印、搜索、刷新
	 * 
	 * @param tableName
	 * @param bean
	 * @param pid
	 * @param buttonPermission
	 * @param specialPermission
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws NoSuchFieldException
	 * @throws IllegalAccessException
	 * @throws IOException
	 * @throws ServletException
	 * @throws InstantiationException
	 */
	public StringBuilder emptyToolBarButton() throws SecurityException,
			IllegalArgumentException, NoSuchFieldException,
			ClassNotFoundException, IllegalAccessException, ServletException,
			IOException, InstantiationException {
		StringBuilder plain = new StringBuilder(
				"<div style='margin-bottom:5px'>");
		String requestUrl = request.getRequestURI();

		// TODO 后续URL中间部分包含find,待优化
		// TODO button控件显示需根据url内的权限进行判断，待优化
		if (Constant.hasPath(route + ".perf.button")) {
			ConfigList buttonList = Constant.getList(route + ".perf.button");
			if (buttonList != null) {
				for (int i = 0; i < buttonList.size(); i++) {
					Config bc = buttonList.get(i).atKey("button");
					String bn = Constant.get(bc, "button.name");
					if (StringUtils.isNotEmpty(bn)) {
						normalButtonBuilder(plain, bc, bn);
					}
					List<String> bns = Constant.getStringList(bc,
							"button.names");
					for (String one : bns) {
						normalButtonBuilder(plain, bc, one);
					}
					String fbn = Constant.get(bc, "button.fullname");
					// TODO 在一个页面上增加一个新的按钮，相当于之前的perfPermission
				}
			}
		}

		printButton(plain);
		searButton(plain);
		reloadButton(plain);
		plain.append("</div>");
		// if (StrUtil.requestParamsNotEmpty(from)) {
		// plain.append(linkButton).append("df_cls()'>带值返回</a>");
		// plain.append(JsUtil.addScript(clsJs()));
		// }
		return plain;
	}

	public void reloadButton(StringBuilder plain) {
		boolean pbShow = true;
		if (Constant.hasPath(route + ".perf.reloadButton")) {
			String pb = Constant.get(route + ".perf.reloadButton");
			if (StringUtils.equals(pb, "false")) {
				pbShow = false;
			}
		}
		if (pbShow) {
			plain.append(linkButton)
					.append("javascript:window.document.location.reload()'><i class=\"icon-repeat\"></i>刷新</a>");
		}
	}

	public void searButton(StringBuilder plain) {
		boolean pbShow = true;
		if (Constant.hasPath(route + ".perf.searButton")) {
			String pb = Constant.get(route + ".perf.searButton");
			if (StringUtils.equals(pb, "false")) {
				pbShow = false;
			}
		}
		if (pbShow) {
			plain.append(linkButton)
					.append(JspUtil3.tableListJsMethod(getTableName()))
					.append("' ><i class=\"icon-search\"></i>搜索</a>");
		}
	}

	public void printButton(StringBuilder plain) {
		boolean pbShow = true;
		if (Constant.hasPath(route + ".perf.printButton")) {
			String pb = Constant.get(route + ".perf.printButton");
			if (StringUtils.equals(pb, "false")) {
				pbShow = false;
			}
		}
		if (pbShow) {
			plain.append(linkButton).append("window.print();'>打印</a>");
		}
	}

	public void normalButtonBuilder(StringBuilder plain, Config bc, String bn)
			throws ServletException, IOException, ClassNotFoundException,
			InstantiationException, IllegalAccessException,
			NoSuchFieldException {
		String buri = StrUtil.dot(header, bn);
		boolean isShow = DealPermission.permissionClazz(buri, request, service,
				omService).getCanIn();
		if (isShow) {
			String jsName = getTableName() + "_" + bn + "()";
			String descr = Constant.get(bc, "button.descr");
			String url = StringUtils.replace(buri, ".", "/");
			if (StringUtils.equals(bn, "add")) {
				if (StringUtils.isEmpty(descr)) {
					descr = Constant.get("JSP_ADD");
				}
				plain.append(linkButton).append(jsName).append("'>")
						.append(descr).append("</a>");
				String pre = request.getParameter("p_re");
				plain.append(JsUtil.addScript(findAddJs(jsName, url, pre,
						request)));

			} else if (StringUtils.equals(bn, "edit")) {
				if (StringUtils.isEmpty(descr)) {
					descr = Constant.get("JSP_EDIT");
				}
				plain.append(linkButton).append(jsName).append("'>")
						.append(descr).append("</a>");
				plain.append(JsUtil.addScript(openUrlByOneRowJs(getTableName(),
						jsName, url)));
			} else if (StringUtils.equals(bn, "get")) {
				if (StringUtils.isEmpty(descr)) {
					descr = Constant.get("JSP_DETAIL");
				}
				plain.append(linkButton).append(jsName).append("'>")
						.append(descr).append("</a>");
				plain.append(JsUtil.addScript(openUrlByOneRowJs(getTableName(),
						jsName, url)));

			} else if (StringUtils.equals(bn, "del")) {
				if (StringUtils.isEmpty(descr)) {
					descr = Constant.get("JSP_DEL");
				}
				plain.append(linkButton).append(jsName).append("'>")
						.append(descr).append("</a>");
				plain.append(JsUtil.addScript(findDelJs(getTableName(), jsName,
						url)));
			} else if (StringUtils.equals(bn, "exp")) {
				plain.append(linkButton).append(jsName).append("'>")
						.append("导出").append("</a>");
				plain.append(JsUtil.addScript(exportXlsJs()));
			}
			// else {
			// plain.append(linkButton).append(jsName).append("'>")
			// .append(descr).append("</a>");
			// plain.append(JsUtil.addScript(openUrlByOneRowJs(
			// getTableName(), jsName, button.get("url"))));// TODO
			// // 设定button的访问后台方式--visitType---设定在对应的PERF显示方式中？
			// }
		}
	}

	public String buttonUri(String requestUrl, Map<String, String> button) {
		String url = button.get("url");
		if (StringUtils.isEmpty(url)) {
			url = requestUrl.replace("/list", "/" + button.get("name") + "");
		}
		url = url + Constant.PAGE_PARAM;
		return url;
	}

	private boolean getButtonShow(String buttonUri)
			throws ClassNotFoundException, InstantiationException,
			IllegalAccessException, ServletException, IOException {
		DealPermission dealPermission = DealPermission.permissionClazz(request,
				service, omService);
		return dealPermission.getCanIn();
	}

	/**
	 * 父页面关闭时调用的js方法 返回父页面选中的bean的id和DF_DESCR
	 * 
	 * @param from
	 * @param clazz2
	 * @param className
	 * @return
	 */
	public StringBuilder clsJs() throws ClassNotFoundException,
			SecurityException, NoSuchFieldException, IllegalArgumentException,
			IllegalAccessException {
		StringBuilder res = new StringBuilder();
		String value = "id";
		String descr = "descr";

		// 确定pop返回字段内容
		String valueName = request.getParameter("_value");
		String descrName = request.getParameter("_descr");

		if (StrUtil.requestParamsNotEmpty(valueName))
			value = valueName;
		if (StrUtil.requestParamsNotEmpty(descrName))
			descr = descrName;
		if (StrUtil.requestParamsNotEmpty(from)) {
			res.append(
					"function df_cls() { var returnvalues='';var ids='';var descrs='';var rows = $('#")
					.append(getTableName())
					.append("').datagrid('getSelections');if(rows.length>0){for(var i=0; i<rows.length; i++){ if(ids=='') {ids=rows[i].")
					.append(value)
					.append(";descrs=rows[i].")
					.append(descr)
					.append(";}else {ids = ids+','+rows[i].")
					.append(value)
					.append(";descrs = descrs+','+rows[i].")
					.append(descr)
					.append(";}} returnvalues=descrs+';'+ids;window.returnValue = returnvalues;window.close();}else{alert('")
					.append(ROWNOTSELECTED_TRIP).append("');}}");
			res.append("\r $(document).ready(function () { $('#")
					.append(getTableName())
					.append("').datagrid({")
					.append("onClickRow: function (rowindex,rowdata){")
					.append("\r var id=rowdata.")
					.append(value)
					.append("; var descr=rowdata.")
					.append(descr)
					.append(";\r if(document.getElementById(id)==null) ")
					.append("{ \r var ap=\"<div><input type='button' id='\"+id+ \"' value='\"+descr+\"'></div>\";")
					.append("$('#bt').append(ap); ")
					.append("}else{\r var el=document.getElementById(id);\r el.parentNode.remove();}}})});");
		}
		return res;
	}

	public StringBuilder findDelJs(String tableName, String jsName, String url) {
		StringBuilder res = new StringBuilder();
		res.append("function ")
				.append(jsName)
				.append("{ var j=1; var rows = $('#")
				.append(tableName)
				.append("').datagrid('getSelections'); if(rows.length>0) {$.messager.confirm('确认框', '确认删除选中记录?', function(r){ if (r) { var ids=''; for(var i=0; i<rows.length; i++){ if(ids=='') ids=rows[i].id;else ids = ids+','+rows[i].id;}$.post('")
				.append(url)
				.append("&_ids='+ids, function(data) {var msg=data['msg'];var delresult=data['delresult'];alert(msg);using(['dialog','messager'], function(){$.messager.show({title:'提示',msg:msg}); if(delresult=='success') {var index = $('#")
				.append(tableName)
				.append("').datagrid('getRowIndex', row);$('#")
				.append(tableName)
				.append("').datagrid('deleteRow', index);}});});}});} else{alert('")
				.append(ROWNOTSELECTED_TRIP).append("');}}");
		return res;
	}

	public StringBuilder searJs() throws SecurityException,
			ClassNotFoundException, IllegalArgumentException,
			IllegalAccessException, InstantiationException,
			NoSuchFieldException, InvocationTargetException,
			NoSuchMethodException {
		// String idField = tl.getIdField();
		StringBuilder res = new StringBuilder();
		StringBuilder cols = new StringBuilder();
		StringBuilder params = new StringBuilder();
		cols.append("{field:'ck',checkbox:true},");
		for (PerfProperty pp : listPl) {
			Property property = pp.getProperty();
			String field = property.getProperty();
//			String votype = property.getVotype();
//			if (StringUtils.isNotEmpty(votype)) {
//				field += "." + Constant.SGABS;
//			}
			String esh = pp.getEsh();

			String fom = "";
			String hid = "";
			int indexOf = field.indexOf(".");
			if (indexOf >= 0) {
				String child = field.substring(indexOf + 1, field.length());
				String f1 = field.substring(0, indexOf);
				fom = ",formatter: function(value,rec){if(rec." + f1
						+ "==null){return '';}return rec." + f1 + "['" + child
						+ "']}";
			}
			if ("0".equals(esh)) {
				hid = ",hidden:true";
			}
			String width = JspUtil3.propertyValue(pp, "width");
			StringBuilder wsb = new StringBuilder();
			if (StringUtils.isNotEmpty(width)) {
				wsb.append(",width:").append(width);
			}
			cols.append("{field:'").append(field).append("'").append(wsb)
					.append(",sortable:true,title:'");
			if (StringUtils.isNotEmpty(pp.getDescr()))
				cols.append(pp.getDescr());
			else
				cols.append(property.getDescr());
			cols.append("'").append(fom).append(hid).append("},");
		}
		for (PerfProperty pp : searchPl) {
			Property property = pp.getProperty();
			String field = property.getProperty();
			if (StringUtils.isNotEmpty(property.getVotype())) {// 对于类搜索，类的id作为搜索条件
				field += ".id";
			}
			params.append("'").append(field).append("':").append("$('#")
					.append(getTableName()).append("_tb input[name=\"")
					.append(field).append("\"]').val(),");
		}
		// params.append("'isPage':'1',");
		params.append("'_sql':$('#sql').val(),");
		if (StringUtils.isNotEmpty(pre)) {
			// String[] rs = StringUtils.split(pre, "$");
			// params.append("'").append(rs[0]).append("':").append(rs[1]).append(",");
			params.append("'p_re':'").append(pre).append("',");
		}
		// params.append("'bean.id':$('#parmaValue').val(),");
		if (StringUtils.isNotEmpty(cols.toString())) {
			cols.deleteCharAt(cols.length() - 1);
		}
		if (StringUtils.isNotEmpty(params.toString())) {
			params.deleteCharAt(params.length() - 1);
		}
		// // 当作为弹出框时，增加翻页多选功能
		StringBuilder idfieldBuilder = new StringBuilder();
		// if (StringUtils.isNotEmpty(idField)) {
		// idfieldBuilder.append("idField:'").append(idField).append("',");
		// } else if (StrUtil.requestParamsNotEmpty(from)) {
		// idfieldBuilder.append("idField:'id',");
		// }
		String pageSize = "100";
		res.append("function ")
				.append(JspUtil3.tableListJsMethod(getTableName()))
				.append("{$('#")
				.append(getTableName())
				.append("').datagrid({emptyMsg:'no records found',toolbar:'#")
				.append(JspUtil3.listTableToolBarName(getTableName()))
				.append("',pageList:[100,50,20,10],onLoadSuccess:function(data){var rows=data['rows'];var len = rows.length;var ind = 0;var ids='';while(ind<len){var r=rows[ind];ids+=r['id']+',';ind++;}$('#ids').val(ids);},"
						+ "showFooter: true,nowrap: false,pageSize:'"
						+ pageSize
						+ "',singleSelect:false,fit:true,pagination:true,rownumbers:true,checkOnSelect:true,selectOnCheck:true,")
				.append(idfieldBuilder).append("url:'").append(url)
				.append("',queryParams:{").append(params)
				.append("},columns:[[").append(cols).append("]]});}");
		return res;
	}

	/*
	 * public static StringBuilder openUrlByOneRowJs(String tableName,String
	 * jsName, String url) { StringBuilder res = new StringBuilder(); String
	 * grid = "$('#" + tableName + "')"; res.append("function ") .append(jsName)
	 * .append("{var row = ") .append(grid) .append(
	 * ".datagrid('getSelected');if(row){var ids=$('#ids').val();var id = row.id;window.open('"
	 * ) .append(url) .append("&id='+id+'&_ids='+ids,'_blank');}else{alert('")
	 * .append(ROWNOTSELECTED_TRIP).append("');}}"); return res; }
	 */
	public StringBuilder openUrlByOneRowJs(String tableName, String jsName,
			String url) {
		StringBuilder res = new StringBuilder();
		String grid = "$('#" + tableName + "')";
		res.append("function ")
				.append(jsName)
				.append("{var rows = ")
				.append(grid)
				.append(".datagrid('getSelections');if(rows.length>0){ var ids=$('#ids').val(); var id = ''; var editids=''; for(var i=0; i<rows.length; i++){ if(editids=='') {editids=rows[i].id;id=rows[i].id;}else editids = editids+','+rows[i].id;} var url1='")
				.append(url)
				.append("'; var url2=url1+'?id='+id+'&_ids='+ids+'&_editids='+editids;")
				.append("layer.open({type: 2,maxmin: true,shadeClose: true,area : ['510px' , '510px'],content: url2});}else{alert('")
				.append(ROWNOTSELECTED_TRIP).append("');}}");
		return res;
	}

	/**
	 * 新增一个Bean方法
	 * 
	 * 弹出一个新页面
	 * 
	 * @param qb
	 *            在Quote页面点击新增后，增加相关属性，以在下一个页面使用
	 * @param url
	 * @param jsName
	 * @return
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws IllegalArgumentException
	 * @throws SecurityException
	 */
	private static StringBuilder findAddJs(String jsName, String url,
			Object bean, HttpServletRequest request) {
		StringBuilder res = new StringBuilder();
		String pre = request.getParameter("p_re");
		if (StringUtils.isNotEmpty(pre)) { // 仅用于ID关联新增的情况，若用其他属性进行关联时，需定义另外的配置变量用于新增页面关联到父页面
			String as = pre.replace("this_.", "");
			int i = as.indexOf("=");
			String property = as.substring(0, i);
			String id = as.substring(i + 1);
			String add = "&" + property + ".id=" + id;
			// res.append("function ").append(jsName).append("{window.open('")
			// .append(url).append(add).append("','_blank');}");
			res.append("function ")
					.append(jsName)
					.append("{layer.open({type: 2, title: 'iframe父子操作',maxmin: true,"
							+ "shadeClose: true,area : ['800px' , '520px'],content: '")
					.append(url).append("'});}");
		} else {
			// res.append("function ").append(jsName).append("{window.open('")
			// .append(url).append("','_blank');}");
			res.append("function ")
					.append(jsName)
					.append("{layer.open({type: 2, title: 'iframe父子操作',maxmin: true,"
							+ "shadeClose: true,area : ['800px' , '520px'],content: '")
					.append(url).append("'});}");
		}
		return res;
	}

	// public Perf getPerf() {
	// return perf;
	// }
	//
	// public void setPerf(Perf perf) {
	// this.perf = perf;
	// }

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

}
